const mysql = require('mysql2')
/**
 * 测试连接
 */
export async function testConnection(dbEntity) {
  let result = false
  try {
    const connection = await getConn(dbEntity)
    connection.destroy()
    result = true
  } catch (e) {
    result = false
  }
  return result
}


/**获取连接 */
async function getConn(dbEntity) {
  const connection = defConn(dbEntity)
  await new Promise((resolve, reject) => {
    connection.connect((error) => {
      if (error) {
        console.log(error)
        reject()
      } else {
        resolve()
      }
    })
  })
  return connection
}

/**
 * 默认
 * @param {*} dbConfig 
 * @returns 
 */
function defConn(dbConfig) {
  return mysql.createConnection({
    host: dbConfig.host,
    port: dbConfig.port,
    user: dbConfig.user,
    password: dbConfig.password,
    database: dbConfig.database
  })
}
